#!/usr/bin/env python
# coding: utf-8

# ## 语音合成API调用

# In[6]:


# coding=utf-8

import sys
import json

# 保证兼容python2以及python3
IS_PY3 = sys.version_info.major == 3
if IS_PY3:
    from urllib.request import urlopen
    from urllib.request import Request
    from urllib.error import URLError
    from urllib.parse import urlencode
    from urllib.parse import quote_plus
else:
    import urllib2
    from urllib import quote_plus
    from urllib2 import urlopen
    from urllib2 import Request
    from urllib2 import URLError
    from urllib import urlencode

# 替换你的 API_KEY
API_KEY = 'iOl610KUWtmQOQMzOEkLrfGv'

# 替换你的 SECRET_KEY
SECRET_KEY = 'aEH5sWvYTTk6kV2yo1IWSWIfYOFGRNDv'

# 提字内容文本
TEXT = "1 【性状】本品为无色至黄色澄清液体;气芳香。2 【功能主治】祛风解毒,消肿止痛。用于感冒头痛,虫蚊咬伤,无名肿毒,舟车眩晕。3 【规格】每瓶装2.5毫升4 【用法用量】外用,涂搽相应穴位或患处。感冒头痛建议涂搽太阳穴、风池穴、合谷穴;舟车眩晕建议涂搽风池穴、5 内关穴、水分穴、天枢穴;虫蚊咬伤、无名肿毒涂搽患处。6 【不良反应】尚不明确。7 【禁忌】尚不明确。"
                                                                                                                                                                                                                                                                                                                                                                           


TTS_URL = 'http://tsn.baidu.com/text2audio'

"""  TOKEN start """

TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'


"""
    获取token
"""
def fetch_token():
    params = {'grant_type': 'client_credentials',
              'client_id': API_KEY,
              'client_secret': SECRET_KEY}
    post_data = urlencode(params)
    if (IS_PY3):
        post_data = post_data.encode('utf-8')
    req = Request(TOKEN_URL, post_data)
    try:
        f = urlopen(req, timeout=5)
        result_str = f.read()
    except URLError as err:
        print('token http response http code : ' + str(err.code))
        result_str = err.read()
    if (IS_PY3):
        result_str = result_str.decode()


    result = json.loads(result_str)

    if ('access_token' in result.keys() and 'scope' in result.keys()):
        if not 'audio_tts_post' in result['scope'].split(' '):
            print ('please ensure has check the tts ability')
            exit()
        return result['access_token']
    else:
        print ('please overwrite the correct API_KEY and SECRET_KEY')
        exit()


"""  TOKEN end """

if __name__ == '__main__':

    token = fetch_token()

    tex = quote_plus(TEXT)  # 此处TEXT需要两次urlencode

    params = {'tok': token, 'tex': tex, 'cuid': "quickstart",
              'lan': 'zh', 'ctp': 1}  # lan ctp 固定参数

    data = urlencode(params)

    req = Request(TTS_URL, data.encode('utf-8'))
    has_error = False
    try:
        f = urlopen(req)
        result_str = f.read()

        headers = dict((name.lower(), value) for name, value in f.headers.items())

        has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)
    except  URLError as err:
        print('http response http code : ' + str(err.code))
        result_str = err.read()
        has_error = True

    save_file = "error.txt" if has_error else u'文字内容信息.mp3'

    with open(save_file, 'wb') as of:
        of.write(result_str)

    if has_error:
        if (IS_PY3):
            result_str = str(result_str, 'utf-8')
        print("tts api  error:" + result_str)

    print("file saved as : " + save_file)


# In[ ]:





# In[ ]:





# In[ ]:





# ## 通用文字识别api调用

# In[33]:


# encoding:utf-8
import requests 

# client_id 为官网获取的AK， client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=3HznrNAPG7VDy01xAhba6QGY&client_secret=F6emkoHCR9HK7fIn1cOUhkXn3bWqOlYM'
response = requests.get(host)
if response:
    print(response.json())


# In[34]:


#'access_token': '24.910e1eb7b1e3104296cf1b1fda738608.2592000.1613582938.282335-23554259'


# In[38]:


#!/usr/bin/env python
# encoding: utf-8
import urllib.parse, urllib.request, base64
access_token = '24.910e1eb7b1e3104296cf1b1fda738608.2592000.1613582938.282335-23554259'
# +替换access_token
url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=' + '24.910e1eb7b1e3104296cf1b1fda738608.2592000.1613582938.282335-23554259' 
# 二进制方式打开图文件
f = open(r'C:/Users/18018/Desktop/图/picture.jpg', 'rb')#本地图片
# 参数image：图像base64编码
img = base64.b64encode(f.read())
params = {"image": img}
params = urllib.parse.urlencode(params).encode(encoding='UTF8')
request = urllib.request.Request(url, params)
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
response = urllib.request.urlopen(request)
content = response.read()
if (content):
    print((content).decode())


# In[ ]:





# ## 自然语言处理--文章标签API调用

# In[ ]:





# In[39]:


# encoding:utf-8
import requests 
# 获取access_token
# client_id 为官网获取的AK， client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=l8H62Gt8frhzKGvPpmwfotdD&client_secret=nnwbHR9Yv5VzU0rrOgLjHcf63nzGT8Sp'
response = requests.get(host)
if response:
    print(response.json())


# In[ ]:


# 'access_token': '24.bc36674c2b179299e11740c60e8c987b.2592000.1613583836.282335-23023731'


# In[ ]:





# In[1]:



import requests
import json

from tornado.escape import json_decode

# access_token='24.bc36674c2b179299e11740c60e8c987b.2592000.1613583836.282335-23023731'
def Tag(title,content):
    tag=''

    APIKey='l8H62Gt8frhzKGvPpmwfotdD'
    secret='nnwbHR9Yv5VzU0rrOgLjHcf63nzGT8Sp'

    host='https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+APIKey+'&client_secret='+secret
    response = requests.get(host)
    if response:
        print(response.json()['access_token'])
    kv={
        'accept-encoding': 'gzip, deflate',
        'x-bce-date': '2015-03-24T13:02:00Z',
        'connection': 'keep-alive',
        'accept': '*/*',
        'host': 'aip.baidubce.com',
        'x-bce-request-id': '73c4e74c-3101-4a00-bf44-fe246959c05e',
        'content-type': 'application/json',
        'authorization': 'bce-auth-v1/46bd9968a6194b4bbdf0341f2286ccce/2015-03-24T13:02:00Z/1800/host;x-bce-date/994014d96b0eb26578e039fa053a4f9003425da4bfedf33f4790882fb4c54903'
    }
    params = {
        "title":title,
        "content": content
    }
    text=json.dumps(params)
    # print(type(text))
    url='https://aip.baidubce.com/rpc/2.0/nlp/v1/keyword?charset=UTF-8&access_token='+response.json()['access_token']
    response1=requests.post(url,headers=kv,timeout=5,data=text)
    if response1:
        result=json.dumps(response1.json(), sort_keys=True, indent=4, ensure_ascii=False)
        print(result)
        result1=json_decode(result)
        for i in result1['items']:
            tag+=i['tag']+' '
    return tag

if __name__=="__main__":
    print(Tag("严厉打击以互联网金融名义进行的违法犯罪","从最高人民法院获悉，最高法近日印发《最高人民法院关于进一步加强金融审判工作的若干意见》，就人民法院加强金融审判工作，保障经济和金融良性循环健康发展提出了30项意见。意见规定，依法认定互联网金融所涉具体法律关系，据此确定各方当事人之间的权利义务。依法严厉打击涉互联网金融或者以互联网金融名义进行的违法犯罪行为，规范和保障互联网金融健康发展。意见提出，要以服务实体经济作为出发点和落脚点，引导和规范金融交易。要遵循经济、金融的发展规律，以金融服务实体经济为价值本源，依法审理各类金融案件。对于能够实际降低交易成本，实现普惠金融，合法合规的金融交易模式依法予以保护。对于以金融创新为名掩盖金融风险、规避金融监管、进行制度套利的金融违规行为，要以其实际构成的法律关系确定其效力和权利义务。对于以金融创新名义非法吸收公众存款或者集资诈骗，构成犯罪的，依法追究刑事责任。在降低实体经济成本、解决实体经济融资难的问题上，意见提出严格依法规制高利贷，对超过民间借贷利率司法保护上限的利息不予保护，以降低实体经济融资成本。依法审理证券、期货民商事纠纷案件，规范资本市场投融资秩序，引导把更多金融资源配置到经济社会发展的重点领域和薄弱环节，更好满足实体经济多样化的金融需求。准确适用保险法审理保险合同纠纷案件，促进保险业发挥长期稳健风险管理和保障的功能。非法集资行为危害人民群众财产安全和社会稳定，打击惩治非法集资行为是防范金融风险的重点。意见对此提出，要依法公正高效审理非法集资案件，持续保持对非法集资犯罪的高压态势。针对非法集资犯罪案件参与人数多，涉案金额大，波及面广，行业和区域相对集中的特点，加强与职能机关、地方政府的信息沟通和协调配合，提升处置效果，切实保障被害人的合法权益，有效维护社会稳定。据了解，人民法院将根据金融机构分布和金融案件数量情况，在金融案件相对集中的地区选择部分法院设立金融审判庭，探索实行金融案件的集中管辖。在其他金融案件较多的中级法院，可以根据案件情况设立专业化的金融审判庭或者金融审判合议庭。"))


# In[ ]:





# In[65]:




import json
import requests

APIKey='l8H62Gt8frhzKGvPpmwfotdD'
SecretKey='nnwbHR9Yv5VzU0rrOgLjHcf63nzGT8Sp'

#创建请求url
def get_url():
    url=0
    #通过API Key和Secret Key获取access_token
    AccessToken_url='https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'.format(APIKey,SecretKey)
    res = requests.post(AccessToken_url)#推荐使用post
    json_data = json.loads(res.text)
    #print(json.dumps(json_data, indent=4, ensure_ascii=False))
    if not json_data or 'access_token' not in json_data:
        print("获取AccessToken的json数据失败")
    else:
        accessToken=json_data['access_token']
        #将得到的access_token加到请求url中
        url='https://aip.baidubce.com/rpc/2.0/nlp/v1/keyword?charset=UTF-8&access_token={}'.format(accessToken)
    return url

#创建请求，获取数据
def get_tag(url,title,content):
    tag=''#存储得到的关键词
    #创建Body请求
    body={
        "title": title,
        "content":content
    }
    body2 = json.dumps(body)#将字典形式的数据转化为字符串,否则报错
    #创建Header请求
    header={
        'content-type': 'application/json'
    }
    res = requests.post(url,headers=header,data=body2)# 推荐使用post
    json_data = json.loads(res.text)
    if not json_data or 'error_code' in json_data:
        #print(json.dumps(json_data, indent=4, ensure_ascii=False))
        print("获取关键词的Json数据失败")
    else:
        #print(json.dumps(json_data, indent=4, ensure_ascii=False))
        for item in json_data['items']:
            tag=tag+item['tag']+' '
        tags=tag.strip()#去除前后空格
        print(tags)
        return tags

if __name__ == '__main__':
    title='iphone手机出现“白苹果”原因及解决办法，用苹果手机的可以看下'
    content='如果下面的方法还是没有解决你的问题建议来我们门店看下成都市锦江区红星路三段99号银石广场24层01室。在通电的情况下掉进清水，这种情况一不需要拆机处理。尽快断电。用力甩干，但别把机器甩掉，主意要把屏幕内的水甩出来。如果屏幕残留有水滴，干后会有痕迹。^H3 放在台灯，射灯等轻微热源下让水分慢慢散去。'
    url=get_url()
    get_tag(url, title,content)


# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# ## 百度翻译开放平台api调用

# In[48]:


#百度通用翻译API,不包含词典、tts语音合成等资源，如有相关需求请联系translate_api@baidu.com
# coding=utf-8
 
import http.client
import hashlib
import urllib
import random
import json
 
appid = '20210117000674265'  # 填写你的appid
secretKey = 'Tva0OjFgT1ETvJBwgagj'  # 填写你的密钥
 
httpClient = None
myurl = '/api/trans/vip/translate'
 
fromLang = 'en'   #原文语种
toLang = 'zh'   #译文语种
salt = random.randint(32768, 65536)
q = 'An old woman had a cat. The cat was very old; she could not run quickly, and she could not bite, because she was so old. One day the old cat saw a mouse; she jumped and caught the mouse. But she could not bite it; so the mouse got out of her mouth and ran away, because the cat could not bite it.Then the old woman became very angry because the cat had not killed the mouse. She began to hit the cat. The cat said, "Do not hit your old servant. I have worked for you for many years, and I would work for you still, but I am too old. Do not be unkind to the old, but remember what good work the old did when they were young.'  #翻译内容
sign = appid + q + str(salt) + secretKey
sign = hashlib.md5(sign.encode()).hexdigest()
myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
salt) + '&sign=' + sign
 
try:
    httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
    httpClient.request('GET', myurl)
 
    # response是HTTPResponse对象
    response = httpClient.getresponse()
    result_all = response.read().decode("utf-8")
    result = json.loads(result_all)
 
    print(result)
 
except Exception as e:
    print(e)
finally:
    if httpClient:
        httpClient.close()


# In[ ]:




